﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace NetPay.WeChat.ProfitSharing
{
    /// <summary>
    /// 分账接收方相关业务处理：新增/删除
    /// </summary>
	public class Receivers
	{
        /// <summary>
        /// 添加分账接收方
        /// </summary>
        /// <param name="type">接收方类型,MERCHANT_ID：商户ID;PERSONAL_OPENID：个人openid（由父商户APPID转换得到）</param>
        /// <param name="account">接收方账号,类型是MERCHANT_ID时，是商户号;类型是PERSONAL_OPENID时，是个人openid类型是PERSONAL_SUB_OPENID时，是个人sub_openid</param>
        /// <param name="name">分账接收方全称,分账接收方类型是MERCHANT_ID时，是商户全称（必传）;当商户是小微商户或个体户时，是开户人姓名;</param>
        /// <param name="relation_type">与分账方的关系类型</param>
        /// <returns></returns>
        public static string AddReceiver(string type, string account, string name, string relation_type)
        {
            // 获取微信支付平台证书公钥
            var certificate = Certificates.GetCertificate();
            var public_key = certificate.Result;

            // 敏感信息加密(分账接收方全称属于敏感信息需要加密)
            byte[] byte_public_key = Encoding.UTF8.GetBytes(public_key);
            var enrypt_name = Authorization.RSAEncrypt(name, byte_public_key);

            SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
            dic.Add("appid", Config.APPID);
            dic.Add("type", type);
            dic.Add("account", account);
            dic.Add("name", enrypt_name);
            dic.Add("relation_type", relation_type);
            // dic.Add("custom_relation", "代理商");
            var data = Newtonsoft.Json.JsonConvert.SerializeObject(dic);

            var url = "https://api.mch.weixin.qq.com/v3/profitsharing/receivers/add";
            var path = System.Environment.CurrentDirectory + "/wwwroot/apiclient_cert.p12";
            X509Certificate2 cert = new X509Certificate2(path, Config.MCHID, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            var serial_no = cert.SerialNumber;

            var result = RequestData(url, data, Config.MCHID, serial_no, public_key);

            return result;
        }

        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="data">数据对象</param>
        /// <param name="mchid">商户ID</param>
        /// <param name="serial_no"></param>
        /// <param name="public_key"></param>
        /// <returns></returns>
        public static string RequestData(string url, string data, string mchid, string serial_no, string public_key)
        {
            var wechatpay_serial_no = "1D99F55A2525B50D10571B129F274FB801769CBB";
            byte[] byte_public_key = Encoding.UTF8.GetBytes(public_key);
            //var encrypt_serial_no = RSAEncrypt("1D99F55A2525B50D10571B129F274FB801769CBB", byte_public_key);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36";
            request.Accept = "application/json";
            string authorization = Authorization.GetAuthorization(url, "POST", data, mchid, serial_no);
            request.Headers.Add("Authorization", authorization);
            request.Headers.Add("Wechatpay-Serial", wechatpay_serial_no);

            byte[] paramJsonBytes;
            paramJsonBytes = Encoding.UTF8.GetBytes(data);
            request.ContentLength = paramJsonBytes.Length;

            Stream writer;
            try
            {
                writer = request.GetRequestStream();
            }
            catch (Exception)
            {
                writer = null;
            }
            writer.Write(paramJsonBytes, 0, paramJsonBytes.Length);
            writer.Close();

            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }

            Stream resStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(resStream);
            string text = reader.ReadToEnd();

            return text;
        }

    }
}

